﻿using System.Configuration;

using Sunyi.Project.WebPoint.Common;
using Sunyi.Project.WebPoint.DataContract;
using System;

namespace Sunyi.Project.WebPoint.ServiceAccess
{
    public sealed class ClientTokenProvider
    {
        private Token token = null;

        public static readonly ClientTokenProvider Instance = new ClientTokenProvider();

        #region Property

        public Token CurrentToken
        {
            get
            {
                if (token == null || token.IsExpired)
                {
                    if (token.ExpirationDate < DateTime.UtcNow.AddMinutes(ServiceAccessHelper.RequestLifeTime)) ApplyToken();
                }

                return token;
            }
        }

        public string UserName
        {
            private get;
            set;
        }

        public string Password
        {
            private get;
            set;
        }

        #endregion

        #region Constructor

        private ClientTokenProvider()
        {
            this.UserName = ConfigurationManager.AppSettings[WebPointGlobalConstant.UserName];
            this.Password = ConfigurationManager.AppSettings[WebPointGlobalConstant.Password];

            // TODO - Any better way to trust certificate in any case?
            System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
        }

        #endregion

        #region Private Method

        private void ApplyToken()
        {
            if (string.IsNullOrEmpty(this.UserName)) return;

            var serviceProxy = new SecurityTokenServiceProxy();
            token = serviceProxy.IssueToken(this.UserName, this.Password);
        }

        #endregion
    }
}
